import router, { constantRoutes, resetRouter } from '@/router'
import { map, nameMap, introduceMap } from '@/router/map'
// import { flatTreeRecursion } from '@/utils/tree'
import { getMenuNav } from '@/api/privilege'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 递归遍历树， 格式化路由，转化为数组
 * @param {*} routes
 */
function flatTreeRecursion(tree) {
  const result = []
  const tag = {}
  tree.forEach(tree => {
    const routesParam = {
      id: tree.menuId,
      parentId: tree.parentId,
      name: nameMap[tree.url]
    }
    if (tree.parentId === '0') {
      routesParam.component = map['layout']
      routesParam.path = '/' + tree.url
      tag[tree.menuId] = tree.url
    } else {
      routesParam.component = map[tree.url]
      routesParam.path = tree.url.replace(tag[tree.parentId] + '/', '')
    }
    routesParam.meta = {
      title: tree.name,
      icon: tree.icon,
      notes: introduceMap[tree.url]
      // noCache: true
    }
    result.push(routesParam)
  })
  return result
}
/**
 * 递归遍历数组， 转化为树
 * @param {*} routes
 */
function buildTreeRecursion(list, parId) {
  const len = list.length
  function loop(parId) {
    const res = []
    for (let i = 0; i < len; i++) {
      const item = list[i]
      if (Number(item.parentId) === Number(parId)) {
        item.children = loop(item.id)
        res.push(item)
      }
    }
    return res
  }
  return loop(parId)
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      getMenuNav({}).then(response => {
        const res = response.data
        let ft = []
        ft = flatTreeRecursion(res.menuList)
        let resRoutes = {}
        resRoutes = buildTreeRecursion(ft, 0)
        commit('SET_ROUTES', resRoutes)
        resolve(resRoutes)
      })
    })
  },
  // 刷新路由
  refreshRoute({ commit, dispatch }) {
    return new Promise(async resolve => {
      resetRouter()
      const accessRoutes = await dispatch('generateRoutes')
      accessRoutes.push({ path: '*', redirect: '/404', hidden: true })
      // dynamically add accessible routes
      router.addRoutes(accessRoutes)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
